<template>
  <div>
    <!-- 功能按钮 -->
    <el-form class="tableSearch" size="mini">
      <el-form-item>
        <el-button type="primary" @click="$router.back(-1)">返回</el-button>
        <el-button type="primary" @click="submitForm('formdata')">保存</el-button>
        <el-button type="primary" @click="openGoodsdialog()">批量添加商品</el-button>
        <el-button type="primary" @click="selectTable.handleMultipleDel()">批量删除商品</el-button>
      </el-form-item>
    </el-form>

    <!-- form表单 -->
    <el-form :model="formdata" :rules="rules" ref="formdata" label-width="120px" size="mini">
      <el-row>
        <el-col :span="8">
          <el-form-item label="指定供应商：" prop="supplierName">
            <el-input v-model="formdata.supplierName" disabled>
              <el-button type="primary" @click="openSuppDialog()" slot="append">选择</el-button>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="收货日期：" prop="receiveDate">
            <el-date-picker v-model="formdata.receiveDate" format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" type="date" placeholder="选择收货日期"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单状态：">
            <el-input v-model="orderStatusArr[formdata.statusFlow]" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="单据日期：">
            <el-date-picker v-model="formdata.orderDate" format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" type="date" disabled></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据编号：">
            <el-input v-model="formdata.purchaseinCode" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格 -->
    <el-table :data="selectTable.tableData" @selection-change="selectTable.handleMultipleSelect">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column type="index" label="#" width="55"></el-table-column>
      <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
      <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
      <el-table-column prop="goodsName" label="商品" align="center" width="200"></el-table-column>
      <el-table-column prop="purchaseUnit" label="单位" align="center"></el-table-column>
      <el-table-column prop="goodsSpec" label="规格型号" align="center">
        <template slot-scope="scope">
          <div v-for="(item, index) in scope.row.goodsSpec" :key="index">
            <span>{{item.paramName}} :</span>
            <span>{{item.paramValue}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="goodsPrice" label="单价" align="center"></el-table-column>
      <el-table-column prop="goodsNum" label="数量" align="center" width="150">
        <template slot-scope="scope">
          <input class="commonInput" v-model="scope.row.goodsNum" size="mini" type="text" style="width:100px" value="1" min="0" maxlength="8" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}">
        </template>
      </el-table-column>
      <el-table-column prop="goodsAmount" label="总价" align="center">
        <template slot-scope="scope">
          <span>{{(scope.row.goodsPrice*scope.row.goodsNum).toFixed(2)}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="selectTable.handleSingleDel(scope.$index)" size="mini">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 费用表单 -->
    <el-form :model="formdata" label-width="120px" size="mini" style="margin-top:25px;">
      <el-row>
        <el-col :span="8">&nbsp;</el-col>
        <el-col :span="8">
          <el-form-item label="操作员：">
            <el-input v-model="formdata.creator" disabled></el-input>
          </el-form-item>
          <el-form-item label="备注：">
            <el-input v-model="formdata.remark" type="textarea" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="总计：">
            <el-input v-model="formdataTotal" disabled></el-input>
          </el-form-item>
          <el-form-item label="运费：">
            <el-input v-model="formdata.freight"></el-input>
          </el-form-item>
          <el-form-item label="应付总计：">
            <el-input v-model="formdataAllTotal" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 供应商弹出框 -->
    <el-dialog title="供应商选择" :visible.sync="supplierClass.dialog" :closeOnClickModal="false" :closeOnPressEscape="false">
      <el-form label-width="0" size="mini">
        <el-form-item>
          <el-button type="primary" @click="handleSeleceSupplier()">选择</el-button>
          <el-button @click="supplierClass.dialog=false">取消</el-button>
        </el-form-item>
        <el-form-item>
          <el-input v-model="selectdata.keywordSupplier" placeholder="请输入供应商名称、编码" style="width:200px;">
            <i slot="suffix" class="el-input__icon el-icon-search" @click="supplierClass.handleSearch(_selectBaseShopPageList, supplierClass.pageData)"></i>
          </el-input>
        </el-form-item>
      </el-form>
      <el-table :data="supplierClass.tableData" highlight-current-row @current-change="supplierClass.handleSingleSelect">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column prop="shopCode" label="供应商编码" align="center"></el-table-column>
        <el-table-column prop="name" label="供应商名称" align="center"></el-table-column>
      </el-table>
      <page-unit :pageData="supplierClass.pageData" :func="_selectBaseShopPageList"></page-unit>
    </el-dialog>

    <!-- 商品选择弹出框 -->
    <el-dialog title="商品选择" :visible.sync="goodsClass.dialog" :closeOnClickModal="false" :closeOnPressEscape="false">
      <el-form label-width="0" size="mini">
        <el-form-item>
          <el-button type="primary" @click="handleSelectGoods()">选择</el-button>
          <el-button @click="goodsClass.dialog=false">取消</el-button>
          <el-alert title="未创建价格协议的商品不可选择!" center type="error" :closable="false" style="display:inline;padding:4px 8px;"></el-alert>
        </el-form-item>
        <el-form-item>
          <el-input v-model="selectdata.keywordGoods" placeholder="输入商品名称或编号" style="width:200px;">
            <i slot="suffix" class="el-input__icon el-icon-search" @click="goodsClass.handleSearch(_findOrderPriceAgreementListPage, goodsClass.pageData)"></i>
          </el-input>
        </el-form-item>
      </el-form>
      <el-table :data="goodsClass.tableData" ref="multipleTable" tooltip-effect="dark" @selection-change="goodsClass.handleMultipleSelect" :row-key="goodsClass.getRowKeys">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column prop="goodsName" label="商品" align="center"></el-table-column>
        <el-table-column prop="purchaseUnit" label="单位" align="center"></el-table-column>
        <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
        <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
        <el-table-column prop="supplierName" label="供应商名称" align="center" width="120"></el-table-column>
        <el-table-column prop="parameter" label="规格型号" align="center">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.goodsSpec" :key="index">
              <span v-if="item!=null">{{item.paramName}} :</span>
              <span v-if="item!=null">{{item.paramValue}}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="isFreight" label="含运费" align="center">
          <template slot-scope="scope">
            <span v-show="scope.row.isFreight=='1'">含运费</span>
            <span v-show="scope.row.isFreight=='0'">不含运费</span>
          </template>
        </el-table-column>
        <el-table-column prop="freight" label="运费" align="center"></el-table-column>
        <el-table-column prop="goodsPrice" label="价格" align="center"></el-table-column>
      </el-table>
      <page-unit :pageData="goodsClass.pageData" :func="_findOrderPriceAgreementListPage"></page-unit>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import s from "@/util/state";
import u from "@/util";
import { TableHandle, autoComputeTotalAll } from "@/util/class";
import sdInput from "@/components/SdInput";
import pageUnit from "@/components/Page";
import {
  saveGoodsPurchase,
  selectBaseShopPageList,
  findOrderPriceAgreementListPage
} from "@/api";

export default {
  components: { sdInput, pageUnit },

  data () {
    return {
      PurchaseType: "",
      selectdata: {
        keywordSupplier: "", // 供应商搜索关键词
        keywordGoods: "" // 商品搜索关键词
      },
      orderStatusArr: s.orderStatusArr, // 订单状态
      formdata: {
        supplierId: "",  // 供应商id
        supplierName: "",  // 供应商名称
        receiveDate: "",  // 收货日期
        statusFlow: "0",  // 订单状态
        orderDate: "",  // 单据日期
        purchaseinCode: "",  // 单据编号
        creator: "",  // 操作员
        remark: "",  // 备注
        purchaseAmount: 0,  // 总计
        freight: 0,  // 运费
        amount: 0,  // 应付总计
      },
      rules: {
        supplierName: [{ required: true, message: "请选择供应商", trigger: "blur" }],
        receiveDate: [{ required: true, message: "请选择收货时间", trigger: "blur" }],
      },
      supplierClass: new TableHandle(),  // 供应商弹窗对象
      goodsClass: new TableHandle(),  // 商品弹窗对象
      selectTable: new TableHandle()  // 弹窗选择后的商品数组
    };
  },

  computed: {
    ...mapState({
      companyName: state => state.companyName,
      merchantId: state => state.merchantId,
      linkName: state => state.linkName,
      mobile: state => state.mobile,
      userId: state => state.userId,
    }),

    // 总计自动计算
    formdataTotal: function () {
      let priceItem = 0,
        freightItem = 0
      this.selectTable.tableData.forEach(i => {
        i.goodsAmount = Number(i.goodsPrice) * Number(i.goodsNum)
        priceItem += i.goodsAmount
        if(Number(i.isFreight) === 0) {
          freightItem +=  Number(i.freight) * Number(i.goodsNum)
        }
      })
      this.formdata.purchaseAmount = isNaN(priceItem) ? 0 : priceItem.toFixed(2)
      this.formdata.freight = isNaN(freightItem) ? 0 : freightItem.toFixed(2)
      return this.formdata.purchaseAmount
    },

    // 应付总计自动计算
    formdataAllTotal: function () {
      return (Number(this.formdata.purchaseAmount) + Number(this.formdata.freight)).toFixed(2)
    },
  },

  mounted () {
    this.init() // 初始化操作员
  },

  methods: {
    init () {
      if (this.linkName != undefined && this.linkName != "") {
        this.formdata.creator = this.linkName
      } else {
        this.formdata.creator = this.mobile
      }
      this.formdata.orderDate = u.getNowFormatDate()
    },

    // 打开供应商弹窗
    openSuppDialog () {
      this._selectBaseShopPageList(this.supplierClass.pageData.pageSize, 1)
      this.supplierClass.dialog = true
    },

    // 获取供应商列表
    _selectBaseShopPageList (pageSize, pageNum) {
      selectBaseShopPageList({
        nameOrCode: this.selectdata.keywordSupplier,
        pageSize: pageSize,
        pageNum: pageNum,
        status: 0,
        businessId: this.merchantId,
        type: 2
      }).then(res => {
        this.supplierClass.tableData = res.data.list
        this.supplierClass.pageData.totalItems = res.data.pageTotal
      });
    },

    // 供应商弹窗点击选择
    handleSeleceSupplier () {
      if (this.supplierClass.isSelect(1, this, '请先选择供应商！')) {
        this.formdata.supplierName = this.supplierClass.singleSelectTable.name
        this.formdata.supplierId = this.supplierClass.singleSelectTable.id
        this.selectTable.tableData = []
        this.supplierClass.dialog = false
      }
    },

    // 打开商品弹窗
    openGoodsdialog () {
      if (this.formdata.supplierId == "") {
        this.$message.error("请先选择供应商")
      } else {
        if(this.goodsClass.multipleSelectTable.length !== 0) {
          this.$refs.multipleTable.clearSelection()
        }
        this._findOrderPriceAgreementListPage(this.goodsClass.pageData.pageSize, 1)
        this.goodsClass.dialog = true
      }
    },

    // 获取商品数据api
    _findOrderPriceAgreementListPage (pageSize, pageNo) {
      findOrderPriceAgreementListPage({
        keyword: this.selectdata.keywordGoods,
        pageSize: pageSize,
        pageNum: pageNo,
        supplierId: this.formdata.supplierId,
        customerId: this.merchantId,
        status: 0,
        agreementType: 1 //协议类型：0-销售价格协议，1-采购价格协议
      }).then(res => {
        this.goodsClass.tableData = res.data.list
        this.goodsClass.pageData.totalItems = res.data.pageTotal
      });
    },

    // 商品弹窗点击选择
    handleSelectGoods () {
      if (this.goodsClass.isSelect(2, this, '请先选择商品！')) {
        this.goodsClass.multipleSelectTable.forEach(i => {
          i.goodsNum = 0
          i.purchasePriceshow = i.purchasePrice
        })
        this.selectTable.tableData = this.goodsClass.handleMultipleConfirm(this.selectTable.tableData, 'goodsId')
        this.goodsClass.dialog = false
      }
    },

    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleSave()
        } else {
          return false
        }
      })
    },

    // 提交表单数据
    handleSave () {
      if (this.selectTable.tableData.length == 0) {
        this.$message.error("商品数量不能为0")
        return false
      }
      if (this.selectTable.tableData.some(i => i.goodsNum < i.minNum)) {
        this.$message.error("数量不能小于最小起订数量")
        return false
      }
      this.selectTable.tableData.forEach(i => {
        i.goodsOrganizationSkuId = i.id
        delete i.createTime
        delete i.updateTime
      });
      if (this.supplierClass.singleSelectTable.isLogin == 0) {
        this.PurchaseType = 2
      } else {
        this.PurchaseType = 1
      }
      saveGoodsPurchase({
        shopId: this.merchantId,
        creator: this.userId,
        supplierId: this.formdata.supplierId,
        supplierName: this.formdata.supplierName,
        receiveDate: this.formdata.receiveDate,
        orderDate: this.formdata.orderDate,
        purchaseinCode: this.formdata.purchaseinCode,
        statusFlow: this.formdata.statusFlow,
        remark: this.formdata.remark,
        purchaseAmount: this.formdata.purchaseAmount,
        freight: this.formdata.freight,
        taxAmount: this.formdata.taxAmount,
        amount: this.formdataAllTotal,
        goodsList: JSON.stringify(this.selectTable.tableData),
        consignee: "",
        shopName: this.companyName,
        linkman: this.supplierClass.singleSelectTable.linkPhone,
        address: ""
      }).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg)
          u.routerTo("/order-center/purchase-management/purchase-procurement")
        }
      });
    },
  }
};
</script>

<style lang="less">
.el-input-group__append {
    background-color: #409eff;
    border-color: #409eff;
    color: #ffffff;
}

.el-dialog__header {
  background-color: #25a0e9;
  .el-dialog__title {
    color: #FFFFFF;
  }
  .el-dialog__close {
    color: #FFFFFF;
    &:hover{
      &:before {
        color: #FFFFFF;
      }
    }
  }
}
</style>


